package ee.karileet.productcatalogue.service.impl;

import ee.karileet.productcatalogue.dao.IProductHome;
import ee.karileet.productcatalogue.dao.impl.ProductHome;
import ee.karileet.productcatalogue.model.Group;
import ee.karileet.productcatalogue.model.Manufactor;
import ee.karileet.productcatalogue.model.Product;
import ee.karileet.productcatalogue.service.IProduct;

public class ProductSrv implements IProduct {

	private IProductHome home;
	
	public ProductSrv() {
		home = new ProductHome();
	}
	
	public boolean addProduct(Product product) {
		// TODO Auto-generated method stub
		return false;
	}

	public Product getProduct(int productId) throws Exception {
		if (!(productId > 0)) throw new Exception("ID must be breater than 0");
		return home.findById(productId);
	}

	public java.util.Set<Product> listGroupProducts(int groupId) throws Exception {
		GroupSrv grpSrv = new GroupSrv();
		Group g = grpSrv.getGroup(groupId);
		return g.getProducts();
	}

	public java.util.Set<Product> listManufactorProducts(int manufactorId) throws Exception {
		ManufactorSrv mnfSrv = new ManufactorSrv();
		Manufactor manufactor = mnfSrv.getManufactor(manufactorId);
		return manufactor.getProducts();
	}
	
	public java.util.HashMap<Manufactor, java.util.Set<Product>> listGroupProductsByManufactor(int groupId) throws Exception {
		GroupSrv grpSrv = new GroupSrv();
		Group g = grpSrv.getGroup(groupId);
		java.util.HashMap<Manufactor, java.util.Set<Product>> retval = new java.util.HashMap<Manufactor, java.util.Set<Product>>();
//		java.util.Set<Product> items = new java.util.HashSet<Product>();
		//find all unique manufactors from products
		for (Product p : g.getProducts()) {
			if(!retval.containsKey(p.getManufactor())) {
				retval.put(p.getManufactor(), new java.util.HashSet<Product>());
			}
		}
		//add products under specific manufactor in hashmap
		for (Product p : g.getProducts()) {
			java.util.Set<Product> items = (java.util.Set<Product>)retval.get(p.getManufactor());
			items.add(p);
		}
		
		return retval;
	}

	public void removeProduct(int productId) throws Exception {
		if (!(productId > 0)) throw new Exception("ID must be greater than 0");
		Product p = home.findById(productId);
		home.delete(p);
	}

	public boolean updateProduct(Product product) {
		// TODO Auto-generated method stub
		return false;
	}

}
